﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;
namespace ZBZH_Manage_Order.Controllers.UserManagement
{
    /// <summary>
    /// 用户钱包
    /// </summary>
    public class UserWalletController : BaseController
    {
        // 保存模型数据
        private static
            Dictionary<string, Order_UserWalt> modelDic = new Dictionary<string, Order_UserWalt>();
        private static
            List<Order_UserWalt> modelList = new List<Order_UserWalt>();
        // 操作员
        private Model.View_OperUser operUser;

        /// <summary>
        /// 获取所有用户钱包列表
        /// </summary>
        /// <returns></returns>
        public List<Order_UserWalt> GetGridData(int pageIndex,int pageSizestring ,string  SearchAccName, string SearchAccCall, string SearchAccIdentifier, string SearchAccCerNub)
        {
            #region 加载表格
            List<Order_UserWalt> list_UserWalt = new List<Order_UserWalt>();
            string result = SRS.GetOrder_UserWalt(pageIndex, pageSizestring, SearchAccName, SearchAccCall, SearchAccIdentifier, SearchAccCerNub, YZM, 1);  // 执行远程请求

            if (!string.IsNullOrEmpty(result) && result.IndexOf("\"BS\":\"1\"") > -1)
            {
                JObject search = JObject.Parse(result);//将服务返回的结果进行优化
                Session["total"] = search["total"].ToString();
                string bsMer = search["BS"].ToString();//获取返回结果是否正常标识
                if (bsMer == "1")//返回结果正常
                {
                    IList<JToken> jieguoMer = search["rows"].Children().ToList();//解析返回的结果
                    if (jieguoMer.Count > 0)
                    {
                        foreach (JToken item in jieguoMer)
                        {
                            Order_UserWalt m = new Order_UserWalt();
                            m.UserWaltID = int.Parse(item["UserWaltID"].ToString());
                            m.AccID = int.Parse(item["AccID"].ToString());
                            m.WaltID = item["WaltID"].ToString();
                            m.WaltNowMoney = DataHelper.MoneyToYuang(item["WaltNowNub"].ToString());
                            m.LastUpTime = item["LastUpTime"].ToString();
                            m.LastUpFlow = item["LastUpFlow"].ToString();
                            m.BZ = item["BZ"].ToString();
                            m.AccNum = item["AccNum"].ToString();
                            m.AccCall = item["AccCall"].ToString();
                            m.AccName = item["AccName"].ToString();
                            m.AccIdentifier = item["AccIdentifier"].ToString();
                            m.AccSex = int.Parse(item["AccSex"].ToString());
                            m.AccCerType = item["AccCerType"].ToString();
                            m.AccCerNub = item["AccCerNub"].ToString();
                            m.IdentityID = item["IdentityID"].ToString();
                            m.CategoryID = item["CategoryID"].ToString();
                            m.SataeID = item["SataeID"].ToString();
                            m.AccCerType_DicName_Login = item["AccCerType_DicName_Login"].ToString();
                            m.DepID = item["DepID"].ToString();
                            m.DepID_DepName_Department = item["DepID_DepName_Department"].ToString();
                            m.IdentityID_DiName_SystemIdentity = item["IdentityID_DiName_SystemIdentity"].ToString();
                            m.CategoryID_DicName_SystemIdentity = item["CategoryID_DicName_SystemIdentity"].ToString();
                            m.StateID_DicName_SystemIdentity = item["StateID_DicName_SystemIdentity"].ToString();
                            m.WaltName = item["WaltName"].ToString();
                            list_UserWalt.Add(m);
                        }
                    }
                }
            }
            return list_UserWalt;
            #endregion
        }

        /// <summary>
        /// 绑定用户钱包datagrid
        /// </summary>
        /// <param name="id"></param>
        /// <param name="jqgridparam">分页参数</param>
        /// <returns></returns>
        public ActionResult InitTable(JqGridParam jqgridparam)
        {
            #region 加载表格
            //Page<Order_UserWalt> page = new Page<Order_UserWalt>();
            //List<Order_UserWalt> list_UserWalt = new List<Order_UserWalt>();
            //int pageIndex = jqgridparam.page;//当前页
            //int pageSize = jqgridparam.rows;
            //list_UserWalt = GetGridData();
            //jqgridparam.records = list_UserWalt.Count;//查询的数据总数

            //var data = new
            //{
            //    total = list_UserWalt.Count,

            //    rows = page.FindListPage(list_UserWalt, ref jqgridparam)//返回当前页的数据
            //};
            //return Json(data);
            return null;
            #endregion
        }

        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public ActionResult getDep()
        {
            ZHHQSERVICE.Service1Client service = new ZHHQSERVICE.Service1Client();
            try
            {
                Model.View_OperUser operUser = Session[SessionStorage.UserLogin] as Model.View_OperUser;
                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                string result = service.GetDepatMentNoValidate("", 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<Basic_Department_T> ls = new List<Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                {
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 查询用户钱包信息
        /// </summary>
        /// <param name="SearchAccName">姓名</param>
        /// <param name="SearchAccCall">手机号</param>
        /// <param name="SearchAccIdentifier">个人编号</param>
        /// <param name="SearchAccCerNub">证件号</param>
        /// <param name="SearchDepID">组织结构ID</param>
        /// <param name="jqgridparam">分页参数</param>
        /// <returns></returns>
        public ActionResult SeachTable(string SearchAccName, string SearchAccCall, string SearchAccIdentifier, string SearchAccCerNub, JqGridParam jqgridparam)
        {
            #region 加载表格
            Page<Order_UserWalt> page = new Page<Order_UserWalt>();
            List<Order_UserWalt> list_UserWalt = new List<Order_UserWalt>();
            int pageIndex = jqgridparam.page;//当前页
            int pageSize = jqgridparam.rows;
            list_UserWalt = GetGridData(pageIndex, pageSize,SearchAccName,SearchAccCall,SearchAccIdentifier,SearchAccCerNub);
            #region MyRegion
            ////姓名
            //if (SearchAccName != "")
            //{
            //    list_UserWalt = list_UserWalt.Where(i => i.AccName.IndexOf(SearchAccName) > -1).ToList();
            //}
            ////电话号
            //if (SearchAccCall != "")
            //{
            //    list_UserWalt = list_UserWalt.Where(i => i.AccCall.IndexOf(SearchAccCall) > -1).ToList();
            //}
            ////个人编号
            //if (SearchAccIdentifier != "")
            //{
            //    list_UserWalt = list_UserWalt.Where(i => i.AccIdentifier.IndexOf(SearchAccIdentifier) > -1).ToList();
            //}
            ////证件号
            //if (SearchAccCerNub != "")
            //{
            //    list_UserWalt = list_UserWalt.Where(i => i.AccCerNub.IndexOf(SearchAccCerNub) > -1).ToList();
            //}
            //部门ID
            //if (SearchDepID != "")
            //{
            //    list_UserWalt = list_UserWalt.Where(i => i.DepID==SearchDepID).ToList();
            //} 
            #endregion
            jqgridparam.records = list_UserWalt.Count;//查询的数据总数
            var data = new
            {
                total = Session["total"],
                rows = list_UserWalt//返回当前页的数据
            };
            return Json(data);
            #endregion
        }

        // 钱包金额编辑
        public ActionResult BtnEdit(UpDateUserWalt1 model)
        {
            #region 金额编辑

            // 获取操作员
            operUser = Session[SessionStorage.OperUser] as Model.View_OperUser;

            if (operUser != null)
            {
                try
                {
                    if (model.tag==2 && model.WaltNowNub + model.updateMoney < 0)
                    {
                        return Content("冲正时，钱包余额不为负数");
                    }
                    else
                    {
                        int topup = model.updateMoney * 100;
                        string result = SRS.SetOrder_UserWalt(operUser.OperID, model.UserWaltID, model.tag, "", topup, model.BZ, GetYZM._YZM, 1);//从接口获得所有流水
                        JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                        string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                        if (bs == "1")//返回结果正常
                        {
                            return Json(bs);
                        }
                        else
                        {
                            return Content(searcho["Msg"].ToString());
                        }
                    
                    }
                    
                }
                catch (Exception e)
                {
                    string error = e.Message;
                    return Json(error);
                }
            }
            else
            {
                //return Json("获取操作员出错！");
                return Json("-1"); //czx:修改为登录者的Session异常时，直接跳转到登录页面 
                          
            }
            #endregion
        }

        // 主页
        public ActionResult Index()
        {
            operUser = Session[SessionStorage.OperUser] as Model.View_OperUser;
            if (operUser != null)
            {
                ViewBag.UserPowers = operUser.RolePower;
                // 身份类型
                ViewBag.AccCerTypeList = GetDicForDictID("18");
                // 部门
                List<SelectListItem> slis = new List<SelectListItem>();
                foreach (Basic_Department_T m in GetDepList(operUser))
                {
                    SelectListItem sli = new SelectListItem();
                    sli.Text = m.DepName;
                    sli.Value = m.DepID;
                    slis.Add(sli);
                }
                ViewBag.DepIDList = slis;
            }
            else
            {
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面               
            }

            return View();
        }

        #region 定义实体类
        /// <summary>
        /// 更新用户钱包信息实体
        /// </summary>
        public class UpDateUserWalt
        {
            public int UserWaltID { get; set; }
            public int tag { get; set; }
            public int updateMoney { get; set; }
            public string BZ { get; set; }
        }

        /// <summary>
        /// 更新用户钱包信息实体+余额
        /// </summary>
        public class UpDateUserWalt1
        {
            public int UserWaltID { get; set; }
            public int tag { get; set; }
            public int updateMoney { get; set; }
            public int WaltNowNub { get; set; }
            public string BZ { get; set; }
        }

        /// <summary>
        /// 重写用户钱包
        /// </summary>
        public class Order_UserWalt : Model.View_Order_UserWalt
        {
            public string WaltNowMoney { get; set; }//界面显示以元为单位的用户余额
        }
        #endregion
    }
}
